import Taro from '@tarojs/taro';
import {Image, View, Picker, Canvas} from '@tarojs/components';
import {connect} from "@tarojs/redux";
import {AtInput, AtTextarea} from 'taro-ui';
import {request, unite} from '../../../utils/index';
import Xia from "../../../asset/myImages/xia.png";
import ImgAdd from "../../../asset/myImages/img_add.png";
import './trainApply.scss';
import None1 from "../../../asset/myImages/img_none.png";


class MyCoupon extends Taro.Component {
    config = {
        navigationBarTitleText: '教练申请入驻',
        backgroundColor: '#fff',
    };

    state = {
        cWidth: 0, //canvas宽
        cHeight: 0, //canvas高

        is_type: false, //false 未提交申请 true 提交申请
        name: '', //姓名
        phone: '', //手机号
        wxPhone: '', //微信号
        sex: 0, //性别 1男 0 女
        timer: '请选择', //出生日期
        timerNext: '请选择', //參加工作時間
        zyzz: '', //专业资质
        imgWrap: [], //个人照片数组
        count: 3, //图片最大张数
        label: '', //标签
        labelName: [], //标签数组
        typeName: '请选择', //区域
        regionId: '', //区域ID
        typeNameText: [], //区域数组
        listResList: [],
    };

    temp = {
        nextBtn: true //防止多次点击上传
    }

    componentDidMount() {
        const {oneAdcodeCode, areaId} = this.props;
        const params = {
            url: '/wx/firstPage/getCityRegionSelect',
            data:{
                adcode: oneAdcodeCode || areaId,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    let name = [];
                    res.data.forEach((item) => {
                        name.push(item.description);
                    });
                    this.setState({
                        typeNameText: name,
                        listResList: res.data,
                    })
                }
            }
        })
    }

    //input内容保存
    datum = (name,val) => {
        this.setState({
            [name]: val
        })
    };

    skipSearch = () => {
        const {label, labelName} = this.state;
        if (labelName.length >= 3) return unite.showToast('标签最多3个');
        if (label) {
            this.setState(prevState => {
                prevState.labelName.push(label);
                return {
                    labelName:  prevState.labelName
                }
            }, () => {
                setTimeout(() => {
                    this.setState({
                        label: '',
                    })
                }, 500);
            })
        }
    };

    closeLabel = (index) => {
        this.setState(prevState => {
            prevState.labelName.splice(index, 1);
            return {
                labelName:  prevState.labelName
            }
        })
    };

    //选择性别
    selectSex = (is) => {
        this.setState({
            sex: is
        })
    };

    //选择出生日期
    onChangeTimer = (name, value) => {
        let time = value.detail.value.replace(/-/g,"/");
        this.setState({
            [name]: time //营业执照有效期
        });
    };

    //选择区域
    onChangeType = (name, res) => {
        const {listResList} = this.state;
        console.log(res);
        if(name == 'typeName') {
            this.setState({
                typeName: listResList[res.detail.value].description,
                regionId: listResList[res.detail.value].regionId,
            });
        }
    };

    //专业资质
    handleChange = (value) => {
        this.setState({
            zyzz: value
        })
    };

    onChangeImg = (files) => {
        this.setState({
            imgWrap: files
        })
    };

    addChooseImg = () => {
        const {imgWrap, count} = this.state;
        if(imgWrap.length < 3){
            if (!this.temp.nextBtn) return;  //防止多次点击
            this.temp.nextBtn = false;  //防止多次点击
            console.log(count + 'count');
            Taro.chooseImage({
                count: count, //上传张数为1
                sizeType: ['original'],
                sourceType: ['album'],
                success: (res) => {
                    for(let i = 0;i<res.tempFilePaths.length;i++) {
                        this.temp.nextBtn = true; //防止多次点击
                        //判断证件大于7M时不执行
                        if(res.tempFiles[i].size > 7340032) {
                            unite.showTipModal(`第${i+1}张图片太大了,请重传`);
                            continue
                        }
                        Taro.getImageInfo({
                            src: res.tempFilePaths[i],
                            success: (data) => {
                                //判断证件大小小于宽度并且为上传手持身份证照时执行, 否则压缩证件
                                if (res.tempFiles[i].size < 2097152) {
                                    this.addImgUrl(res.tempFilePaths[i]);
                                } else {
                                    let widthHeight = unite.imgZoom(data.width, data.height); //利用canvas压缩图片
                                    // let widthHeight = [data.width, data.height]; //利用canvas压缩图片
                                    //----------绘制图形并取出图片路径--------------
                                    this.setCanvas(widthHeight, res.tempFilePaths[i], i);  //Taro.canvasToTempFilePath   Canvas 在子组件中存在bug，所以提到父组件压缩
                                }
                            }
                        });
                    }
                },
                fail: () => {
                    this.temp.nextBtn = true; //防止重复点击
                }
            })
        }else{
            unite.showToast('最多只可添加9张图片')
        }
    };

    //压缩证件
    setCanvas = (widthHeight, value, i) => {
        const {cWidth, cHeight} = this.state;
        // Taro.showLoading({
        //     title: '图片压缩中...' //加载框
        // });
        let ctx = Taro.createCanvasContext('myCanvas', this.$scope);
        ctx.clearRect(0, 0, cWidth, cHeight); //清空画布
        this.setState({
            cWidth:widthHeight.canvasWidth, //赋值压缩后的宽度
            cHeight: widthHeight.canvasHeight //赋值压缩后的高度
        });
        ctx.drawImage(value, 0, 0, widthHeight.canvasWidth, widthHeight.canvasHeight);
        setTimeout(() => {
            ctx.draw(true, () => {
                Taro.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    destWidth: widthHeight.canvasWidth,
                    destHeight: widthHeight.canvasHeight,
                    quality: 0.2,
                    fileType:'jpg',
                    success: (datas) => {
                        this.addImgUrl(datas.tempFilePath);
                        console.log(JSON.stringify(datas.tempFilePath));
                    },
                    fail: () => {
                        unite.showTipModal(`第${i + 1}张图片上传失败,请重传`);
                    },
                    complete: (datas) => {
                        console.log(datas);
                    },
                })
            });   //留一定的时间绘制canvas
            // clearTimeout(clear);
        }, 1000);
    };

    //上传图片
    addImgUrl = (url) => {
        const {userToken} = this.props;
        Taro.uploadFile({
            url: 'https://pro.pmad.com.cn/api/wx/coach/uploadCoachAvatar',
            filePath: url,
            name: 'avatarfile',
            fileType: 'image',
            accessToken: userToken,
            formData: {
                accessToken: userToken,
                avatarfile: url
            },
            success: (ret) => {
                let data = ret.data ? JSON.parse(ret.data) : {};
                if (data.code == 200) {
                    if (data.data.indexOf('http') != -1) {
                        this.setState((pervState) =>({
                            count: pervState.count - 1,
                            imgWrap: pervState.imgWrap.concat(data.data),
                        }), () => {
                            console.log(JSON.stringify(this.state.imgWrap))
                        });
                    } else {
                        unite.showToast(data.data)
                    }
                } else {
                    unite.showToast('图片错误请重新上传')
                }
            },
            fail: (e) => {
                console.log(e);
            }
        });
    };

    //点击删除图片
    deleteImg = (value) => {
        const {imgWrap} = this.state;
        imgWrap.splice(value,1);
        this.setState((pervState) =>({
            count: pervState.count + 1,
            imgWrap,
        }));
    };

    //提交申请
    sumbit = () => {
        const {name, wxPhone, sex, timer, timerNext, zyzz, imgWrap, labelName, regionId, phone} = this.state;
        if (!name) return unite.showTipModal('请输入姓名');
        if (timer == '请选择') return unite.showTipModal('请选择出生日期');
        if (timerNext == '请选择') return unite.showTipModal('请选择參加工作时间');
        if (!regionId) return unite.showTipModal('请选择区域');
        if (labelName.length == 0) return unite.showTipModal('请添加您的标签');
        if (imgWrap.length == 0) return unite.showTipModal('请上传个人照片');
        const params = {
            url: '/wx/coach/apply',
            data:{
                avatar: imgWrap.join(","), //艺人画像
                birthDate: timer, //出生日期格式 (yyyyMMdd）
                // phone, //手机号
                weiXinAccount: wxPhone,
                coachName: name, //艺人名称
                qualification: zyzz, //专业资质
                sexFlag: sex, //性别
                workDate: timerNext, //參加工作时间
                labelNames: labelName, //标签
                regionId, //区域
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    unite.showToast('申请已提交，请耐心等待审核!');
                    setTimeout(() => {
                        Taro.navigateBack({
                            delta: 2
                        })
                    }, 2000)
                }
            }
        })
    };

    render() {
        const {name, wxPhone, sex, timer, timerNext, zyzz, imgWrap, is_type, label, labelName, typeName, typeNameText, phone, cWidth, cHeight} = this.state;
        return (
            <View>
                {is_type ? ( //已提交审核
                    <View className="page">
                        <View className="none-wrap-page">
                            <Image className="none-img" src={None1}/>
                            <View>正在审核中…</View>
                            <View className="none-max-btn" onClick={() => {Taro.navigateBack({delta: 1})}}>返回</View>
                        </View>
                    </View>
                ) : ( //未提交
                    <View className="myPage">
                        <View className="apply-list-wrap">
                            <View className="list-item flex-lr">
                                <View className="flex-top-l">
                                    <View>姓名</View>
                                    <View className="red">*</View>
                                </View>
                                <AtInput
                                    placeholderClass="input-placeholder"
                                    border={false}
                                    name='realName'
                                    type='text'
                                    placeholder='请输入'
                                    value={name}
                                    onChange={this.datum.bind(this, 'name')}
                                    onBlur={this.datum.bind(this, 'name')}
                                />
                            </View>
                            {/*<View className="list-item flex-lr borderTop">*/}
                            {/*    <View className="flex-top-l">*/}
                            {/*        <View>手机号</View>*/}
                            {/*    </View>*/}
                            {/*    <AtInput*/}
                            {/*        placeholderClass="input-placeholder"*/}
                            {/*        border={false}*/}
                            {/*        name='realName'*/}
                            {/*        type='phone'*/}
                            {/*        placeholder='请输入'*/}
                            {/*        value={phone}*/}
                            {/*        onChange={this.datum.bind(this, 'phone')}*/}
                            {/*        onBlur={this.datum.bind(this, 'phone')}*/}
                            {/*    />*/}
                            {/*</View>*/}
                            <View className="list-item flex-lr borderTop">
                                <View className="flex-top-l">
                                    <View>微信号</View>
                                </View>
                                <AtInput
                                    placeholderClass="input-placeholder"
                                    border={false}
                                    name='realName'
                                    type='text'
                                    placeholder='请输入'
                                    value={wxPhone}
                                    onChange={this.datum.bind(this, 'wxPhone')}
                                    onBlur={this.datum.bind(this, 'wxPhone')}
                                />
                            </View>
                        </View>
                        <View className="apply-list-wrap">
                            <View className="list-item flex-lr">
                                <View className="flex-top-l">
                                    <View>性别</View>
                                    <View className="red">*</View>
                                </View>
                                <View className="select-sex flex-lr">
                                    <View className="flex-l" onClick={this.selectSex.bind(this, 1)}>
                                        <View className={`select flex-center ${sex == 1 ? 'selectActive' : ''}`}>
                                            <View className="acitves"></View>
                                        </View>
                                        <View>男</View>
                                    </View>
                                    <View className="flex-r" onClick={this.selectSex.bind(this, 0)}>
                                        <View className={`select flex-center ${sex == 0 ? 'selectActive' : ''}`}>
                                            <View className="acitves"></View>
                                        </View>
                                        <View>女</View>
                                    </View>
                                </View>
                            </View>
                            <View className="list-item flex-lr borderTop">
                                <View className="flex-top-l">
                                    <View>出生日期</View>
                                    <View className="red">*</View>
                                </View>
                                <View className="flex-r">
                                    <Picker className={`picker ${timer === '请选择' ? 'picker-color' : ''}`} mode='date' onChange={this.onChangeTimer.bind(this, 'timer')}>
                                        <View>
                                            {timer}
                                        </View>
                                    </Picker>
                                    <Image mode="widthFix" className="right-icon" src={Xia}/>
                                </View>
                            </View>
                            <View className="list-item flex-lr borderTop">
                                <View className="flex-top-l">
                                    <View>参加工作时间</View>
                                    <View className="red">*</View>
                                </View>
                                <View className="flex-r">
                                    <Picker className={`picker ${timerNext === '请选择' ? 'picker-color' : ''}`} mode='date' onChange={this.onChangeTimer.bind(this, 'timerNext')}>
                                        <View>
                                            {timerNext}
                                        </View>
                                    </Picker>
                                    <Image mode="widthFix" className="right-icon" src={Xia}/>
                                </View>
                            </View>
                            <View className="list-item flex-lr borderTop">
                                <View className="flex-top-l">
                                    <View>区域</View>
                                    <View className="red">*</View>
                                </View>
                                <View className="flex-r">
                                    <Picker className={`picker ${typeName === '请选择' ? 'picker-color' : ''}`} range={typeNameText} onChange={this.onChangeType.bind(this, 'typeName')}>
                                        <View>
                                            {typeName}
                                        </View>
                                    </Picker>
                                    <Image mode="widthFix" className="right-icon" src={Xia}/>
                                </View>
                            </View>
                        </View>
                        <View className="apply-list-wrap">
                            <View className="apply-list-text">专业资质</View>
                            <AtTextarea
                                value={zyzz}
                                onChange={this.handleChange.bind(this)}
                                maxLength={400}
                                count={false}
                                placeholder='建议您填写自我介绍、从业经验、专业证书'
                            />
                            <View className="list-item flex-l borderTop">
                                <View className="flex-top-l">
                                    <View className="bq-text">标签</View>
                                </View>
                                {labelName.length != 0 &&(
                                    <View className="flex-l bq-wrap">
                                        {labelName.map((item, index) => (
                                            <View className="bq-item flex-center" key={index} onClick={this.closeLabel.bind(this, index)}>
                                                {item}
                                                <View className="close">x</View>
                                            </View>
                                        ))}
                                    </View>
                                )}
                                {labelName.length < 3 && (
                                    <View className="input-placeholders">
                                        <AtInput
                                            placeholderClass="input-placeholder"
                                            border={false}
                                            name='realName'
                                            type='text'
                                            maxLength={6}
                                            confirmType="done"
                                            placeholder=''
                                            value={label}
                                            onChange={this.datum.bind(this, 'label')}
                                            onBlur={this.skipSearch}
                                            onConfirm={this.skipSearch}
                                            // onFocus={this.skipSearch}
                                        />
                                    </View>
                                )}
                            </View>
                        </View>
                        <View className="apply-list-wrap">
                            <View className="apply-list-text">个人照片</View>
                            <View className="flex-l apply-list-img">
                                {imgWrap.map((item, index) => (
                                    <View className="select-img-wrap">`
                                        <View className="close-img flex-center" onClick={this.deleteImg.bind(this, index)}>x</View>
                                        <Image mode="widthFix" key={index} className="select-img" src={item}/>
                                    </View>
                                ))}
                                {imgWrap.length < 1 && (
                                    <Image mode="widthFix" onClick={this.addChooseImg} className="select-img" src={ImgAdd}/>
                                )}
                            </View>
                            <View className="apply-btn flex-center" onClick={this.sumbit}>提交申请</View>
                        </View>
                    </View>
                )}
                <Canvas canvasId="myCanvas" style={`width: ${cWidth}px; height: ${cHeight}px; position: absolute; left:-10000px; top:-10000px; z-index: -100`}/>
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {userToken, oneAdcodeCode, areaId} = state;
    return {
        userToken,
        oneAdcodeCode,
        areaId
    }
};

const mapDispatchToProps = {
};

export default connect(mapStateToProps, mapDispatchToProps)(MyCoupon);



